<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 商品steps -->
    <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
    <el-steps :space="200" :active="Number(activeIndex)" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 商品信息表单 -->
    <el-form :model="addedForm" :rules="addedFormRules" ref="addedFormRef" label-width="100px" label-position="top">
      <!-- 商品tabs -->
      <el-tabs v-model="activeIndex" tabPosition="left" :before-leave="tabLeave" @tab-click="tabClicked(activeIndex)">
        <!-- 基本信息tab -->
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addedForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="addedForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量">
            <el-input v-model="addedForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量">
            <el-input v-model="addedForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-cascader
              v-model="addedForm.goods_cat"
              :options="goodsCateList"
              :props="CateProps"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <!-- 商品参数tab -->
        <el-tab-pane label="商品参数" name="1">
          <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
            <!-- 商品参数复选框 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox v-for="(subItem, index) in item.attr_vals" :key="index" :label="subItem"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <!-- 商品属性tab -->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
            <!-- 商品属性输入框 -->
            <el-input v-model="item.attr_vals" type="text"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="http://127.0.0.1:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerObj"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="addedForm.goods_introduce"></quill-editor>
          <!-- 添加商品按钮 -->
          <el-button type="primary" @click="add">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!-- 图片弹出对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="imgURL" :style="{ width: '100%' }">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  created () {
    this.getGoodsCateList()
  },
  methods: {
    async getGoodsCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 3
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取分类列表失败')
      }
      this.goodsCateList = res.data
    },
    /* 级联选择器值改变函数 */
    handleChange () {},
    /* 监听切换tab标签页 */
    tabLeave (activeName, oldActiveName) {
      if (this.addedForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    /* 监听tab被点击时的事件 */
    tabClicked (index) {
      switch (Number(index)) {
        case 1:
          this.getParams()
          break
        case 2:
          this.getAttr()
          break
      }
    },
    /* 获取参数 */
    async getParams () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'many'
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      res.data.forEach(el => {
        el.attr_vals = el.attr_vals ? el.attr_vals.split(',') : []
      })
      this.manyTabData = res.data
    },
    /* 获取属性 */
    async getAttr () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'only'
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败')
      }
      this.onlyTabData = res.data
    },
    /* 点击图片 预览触发事件 */
    handlePreview (file) {
      console.log(file.response.data)
      const url = file.response.data.url
      this.imgURL = url
      this.dialogVisible = true
    },
    /* 移除预览图片触发的事件 */
    handleRemove (file) {
      const res = file.response.data.tmp_path
      this.addedForm.pics.forEach((el, index) => {
        if (el.pic === res) {
          this.addedForm.pics.splice(index, 1)
        }
      })
    },
    /* 图片上传成功时触发事件 */
    handleSuccess (response) {
      const { data: res } = response
      this.addedForm.pics.push({
        pic: res.tmp_path
      })
    },
    /* 添加商品按钮触发事件 */
    add () {
      this.$refs.addedFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写必要的表单项')
        }
        // 处理动态参数
        this.manyTabData.forEach(el => {
          const newInfo = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals.join(' ')
          }
          this.addedForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTabData.forEach(el => {
          const newInfo = {
            attr_id: el.attr_id,
            attr_value: el.attr_vals
          }
          this.addedForm.attrs.push(newInfo)
        })
        // 添加的表单数据预处理
        const cloneForm = _.cloneDeep(this.addedForm)
        cloneForm.goods_cat = cloneForm.goods_cat.join(',')
        /* 发起请求添加商品 */
        const { data: res } = await this.$http.post('goods', cloneForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    /* 级联框选中时第三个分类id */
    cateId () {
      if (this.addedForm.goods_cat.length === 3) {
        return this.addedForm.goods_cat[2]
      }
      return null
    }
  },
  data () {
    return {
      /* steps当前激活的step */
      activeIndex: '0',
      /* 商品信息对象 */
      addedForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      /* 商品信息对象验证规则 */
      addedFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
      },
      /* 商品分类数据 */
      goodsCateList: [],
      /* 级联选择器的选中值 */
      CateArr: [],
      /* 级联选择器属性 */
      CateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      /* 获取到的参数 */
      manyTabData: [],
      /* 获取到的属性 */
      onlyTabData: [],
      /* 上传图片的请求头 */
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      /* 控制图片预览对话框的显示与否 */
      dialogVisible: false,
      /* 图片预览对话框中的图片绝对地址 */
      imgURL: ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
  margin-bottom: 20px;
}
.el-steps {
  margin: 15px 0;
}
.el-button {
  margin-top: 20px;
}
</style>
